﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace UFrame
{
    public class FingersMove : MonoBehaviour
    {
        public Transform cubeTrans;
    
        public float speed = 10f;
        private Vector3 recordPos;
        [Range(0, 100)] public float recordDistance = 10;
        [Range(0, 100)] public float ignoreDistance = 3;
    
        public event Action<TouchData> onTouch;
    
        void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                recordPos = Input.mousePosition;
                onTouch?.Invoke(new TouchData()
                {
                    type = TouchType.Start,
                });
            }
    
            if (Input.GetMouseButton(0))
            {
                var dir = Input.mousePosition - recordPos;
                float dis = Vector3.Distance(recordPos, Input.mousePosition);
    
                if (dis > recordDistance)
                {
                    recordPos = Vector3.Lerp(recordPos, Input.mousePosition, 0.5f);
                }
    
                if (dis < ignoreDistance)        //两个移动之间小于x距离 忽略这次移动,放置出现方向错乱问题
                {
                    return;
                }
    
                Vector3 newDir = new Vector3(-dir.x, 0, -dir.y);
                var d = newDir.normalized * speed * Time.deltaTime;
                onTouch?.Invoke(new TouchData()
                {
                    type = TouchType.End,
                    positionDelta = d,
                });
            }
    
            if (Input.GetMouseButtonUp(0))
            {
                onTouch?.Invoke(new TouchData()
                {
                    type = TouchType.End,
                });
            }
        }
    
        public class TouchData
        {
            public TouchType type;
            public Vector3 positionDelta;
        }
    
        public enum TouchType
        {
            Start,
            Move,
            End,
        }
    }
}
